package com.netty.http.server;

import java.nio.charset.Charset;

import com.netty.http.coder.json.HttpMsgRequestDecoder;
import com.netty.http.coder.json.HttpMsgResponseEncoder;
import com.netty.http.handler.JsonHttpServerHandler;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

public class NettyHttpServerTest {
	int port;
	private String charset = "UTF-8";
	private int timeout=60;

	public NettyHttpServerTest(int port) {
		this.port = port;
	}

	public void start() throws Exception {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		ServerBootstrap b = new ServerBootstrap();
		b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
				.childHandler(new ChannelInitializer<SocketChannel>() {
					@Override
					public void initChannel(SocketChannel ch) throws Exception {
						// server端发送的是httpResponse，所以要使用HttpResponseEncoder进行编码
						ch.pipeline().addLast(new HttpResponseEncoder());
						// server端接收到的是httpRequest，所以要使用HttpRequestDecoder进行解码
						ch.pipeline().addLast(new HttpRequestDecoder());
						ch.pipeline().addLast(new HttpObjectAggregator(1048576));

						ch.pipeline().addLast(new HttpMsgResponseEncoder(charset,timeout));
						ch.pipeline().addLast(new HttpMsgRequestDecoder(charset));
						ch.pipeline().addLast(new JsonHttpServerHandler());
					}
				}).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
		ChannelFuture f = b.bind(port).await();
		if (!f.isSuccess()) {
			System.out.println("无法绑定端口：" + port);
			throw new Exception("无法绑定端口：" + port);
		}

		System.out.println("服务[{}]启动完毕，监听端口[{}]" + port);
		// f.channel().closeFuture().sync();

	}
}
